package com.cdtye.itps.cms.util;

import com.cdtye.common.webcore.util.DateUtil;
import com.cdtye.common.webcore.web.BizException;
import com.cdtye.itps.cms.dao.enums.CommonFileType;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author: jchen
 * @Date: 2021/5/24 15:57
 * @Description:
 */
@Slf4j
public class ExpCommonHelper {

    /**
     * @Author jchen
     * @Date: 17:17 2021/5/24
     * @Description: 导出安全质量统计数据
     * @Param [list, commonFileType]
     * @return org.apache.poi.ss.usermodel.Workbook
    **/
    public  static Workbook exportStaticsData(List<List<String>> list, List<String> headList, CommonFileType commonFileType){
        String fileName  = commonFileType.getFileName();
        Workbook workbook = ExpCommonHelper.getServiceWorkbook(StringUtils.split(fileName,".")[0]+(CollectionUtils.isEmpty(headList)?"":headList.size())+"."+StringUtils.split(fileName,".")[1]);
        Sheet sheet = workbook.getSheetAt(0);
        workbook.setSheetName(0,commonFileType.getText());
        //设置单元格自动换行
        CellStyle style = workbook.createCellStyle();
        style.setWrapText(true);
        style.setVerticalAlignment(VerticalAlignment.TOP);//顶部对齐
        style.setAlignment(HorizontalAlignment.LEFT);//左对齐
        if(commonFileType.getFileName().equals(CommonFileType.EVALAUATION_SUMMARY.getFileName())){
            style.setVerticalAlignment(VerticalAlignment.CENTER);//顶部对齐
            style.setAlignment(HorizontalAlignment.CENTER);//左对齐
        }
        ExpCommonHelper.convertStaticsData(sheet, list, headList,commonFileType,style);
        return workbook;
    }


    public static  void convertStaticsData(Sheet sheet,List<List<String>>  rowList,List<String> headList,CommonFileType commonFileType,CellStyle style){

        for(int i=0;i<headList.size();i++){
            int startRow = 1;
            Row row=sheet.getRow(startRow);
            int w=i*3+1;
            Cell cell= row.getCell(w);
            cell=cell==null?row.createCell(w):cell;
            cell.setCellValue(org.apache.commons.lang3.StringUtils.isEmpty(headList.get(i))?"":headList.get(i).toString());
        }

        int startRow=commonFileType.getStatrRowNo();
        for(int i=0;i<rowList.size();i++){
            List<String> everyRow=rowList.get(i);
            int k=(i==0)?startRow:startRow+i;
            Row row=sheet.getRow(k);
            row=row==null?sheet.createRow(k):row;
            int  startColumn  = commonFileType.getStatrColNo();
            for(int j=0;j<everyRow.size();j++){
                int w=(j==0)?startColumn:startColumn+j;
                Cell cell= row.getCell(w);
                cell=cell==null?row.createCell(w):cell;
                cell.setCellValue(org.apache.commons.lang3.StringUtils.isEmpty(everyRow.get(j))?"":everyRow.get(j).toString());
                cell.setCellStyle(style);
            }
        }
    }


    /**
     * @Author jchen
     * @Date: 17:17 2021/5/24
     * @Description: 获取数据模板
     * @Param [filePath]
     * @return org.apache.poi.ss.usermodel.Workbook
    **/
    public static Workbook getServiceWorkbook(String filePath){
        //只需要 .xls格式的
        try{
            InputStream tempInputStream = ExpCommonHelper.class.getClassLoader().getResourceAsStream(filePath);
            Workbook workbook = new HSSFWorkbook(tempInputStream);
            return workbook;
        }catch (Exception e){
            log.error("没有解析到文件模板",e);
            return null;
        }
    }

    /**
     * 导出模板方法
     *
     * @param response
     * @param resourcePath 模板路径
     * @param fileName     导出的文件名称
     * @return
     * @author nz
     */
    public static void exportTemplate(HttpServletResponse response, String resourcePath, String fileName) {
        try (
                InputStream tempInputStream = ExpCommonHelper.class.getClassLoader().getResourceAsStream(resourcePath);
                OutputStream outputStream = response.getOutputStream();
        ) {
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = tempInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            throw new BizException("导出模板方法报错");
        }
    }

    public static void exportCommonMethod(Workbook workbook, HttpServletResponse response, String fileName) {
        ServletOutputStream outputStream = null;
        try {
            String name = fileName + "[" + DateUtil.getDateString() + "].xls";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new BizException("导出excel出错");
        }finally {
            try {
                if (outputStream != null){
                    outputStream.close();
                }
            }catch (Exception e){
                log.error("导出 : 关闭输出流失败");
            }
        }
    }

    public static void exportCommonMethodNew(Workbook workbook, HttpServletResponse response, String fileName) {
        ServletOutputStream outputStream = null;
        try {
            String name = fileName + ".xls";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new BizException("导出excel出错");
        }finally {
            try {
                if (outputStream != null){
                    outputStream.close();
                }
            }catch (Exception e){
                log.error("导出 : 关闭输出流失败");
            }
        }
    }
}
